package org.itli.wacp.Controller;


import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.itli.wacp.Mapper.UserMapper;
import org.itli.wacp.Result.Result;
import org.itli.wacp.Service.UserService;
import org.itli.wacp.Util.JWTUtil;
import org.itli.wacp.Util.MD5Util;
import org.itli.wacp.Util.ThreadLocalUtil;
import org.itli.wacp.pojo.User;
import org.itli.wacp.vo.PersonInfoVO;
import org.itli.wacp.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Time;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/user")
@Tag(name="用户接口")
@Slf4j
public class UserController {

    private UserService service;
    private User PersonInfo;
    private RedisTemplate redisTemplate;
    String tokenname = "init";
    private String email;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setService(UserService service) {
        this.service = service;
    }

    JWTUtil jwt = new JWTUtil();

    @PostMapping("/login")
    @Operation(summary = "用户登陆")
    public Result<UserVO> Login(@RequestParam String username, @RequestParam String password) {
        log.info("传入：" + username + password);
        //进入service层
        User UserInfo = service.Login(username, password);

        if (UserInfo == null) {
            //查不到直接返回值
            log.error("查不到！"+UserInfo);
            return Result.error("用户名或密码错误！");
        }
        else {
            //存入实体对象
            PersonInfo = UserInfo;

            //生成JWT令牌
            Map<String,Object> JWTMap = new HashMap<>();
            JWTMap.put("username",UserInfo.getId());
            JWTMap.put("name",UserInfo.getName());
            String token = jwt.genToken(JWTMap);
            log.info("生成的令牌为："+token);

            ThreadLocalUtil.set(token);
            tokenname = UserInfo.getId()+"token";

            //将令牌存入redis
            redisTemplate.opsForValue().set(tokenname,token);
            redisTemplate.expire(tokenname,5, TimeUnit.MINUTES);
            //放入返回值实体类中
            UserVO user = UserVO.builder()
                    .id(UserInfo.getId())
                    .name(UserInfo.getName())
                    .token(token)
                    .build();

            return Result.success(user);
        }
    }

    @PostMapping("/regist")
    @Operation(summary = "用户注册")
    public Result Regist(@RequestBody User user){
        log.info("传入"+user);
        int regist = service.Regist(user);
        if(regist == 1){
            return Result.success("注册成功！");
        }
        else if(regist == 404){
            return Result.error("用户已存在!");
        }
        else {
            return Result.error("注册失败！");
        }
    }

    @GetMapping("/MyInfo")
    @Operation(summary = "查询信息")
    public Result<PersonInfoVO> MyInfo(@RequestHeader("Authorization") String token){
        log.info("拿到令牌："+token);
        Map<String,Object> map =  jwt.parseToken(token);//解密jwt令牌
        String id = map.get("username").toString();
        String admin;
        String time = service.Member(id);
        String member;
        if(time == null){
            member = "否";
            time = "无";
        }else {
            member = "是";
        }
        if(PersonInfo.getAdmin() == 0){
            admin = "否";
        }
        else admin = "是";
        PersonInfoVO infovo = PersonInfoVO.builder()
                .name(PersonInfo.getName())
                .sex(PersonInfo.getSex())
                .classes(PersonInfo.getClasses())
                .admin(admin)
                .id(PersonInfo.getId())
                .member(member)
                .MemberTime(time)
                .build();
        return Result.success(infovo);
    }

    @GetMapping("/autologin")
    @Operation(summary = "自动登陆")
    public Result<String> AutoLogin(@RequestHeader("Authorization") String token){
        log.info("Redis令牌为："+redisTemplate.opsForValue().get(tokenname));
        log.info("前端令牌为："+token);
        if(token == null){
            return Result.error("令牌为空");
        }
        else {
            String tokens  = (String) redisTemplate.opsForValue().get(tokenname);
            if(tokens == null){
                return Result.error("服务端令牌过期");
            }
            else if(token.equals(tokens)){
                return Result.success("自动登陆");
            }
            else {
                return Result.error("服务端匹配失败");
            }
        }
    }

    @PostMapping("/JHSendEmail")
    @Operation(summary = "激活账号：发送邮箱")
    public Result JHSendEmail(@RequestHeader("Authorization") String token,@RequestParam String email){
        log.info("前端令牌为："+token);
        log.info("前端Email为："+email);
        Map<String,Object> map =  jwt.parseToken(token);//解密jwt令牌
        String id = map.get("username").toString();
        String s = service.JHSendEmail(id, email);
        return Result.success(s);
    }

    @PostMapping("/JHYZEmail")
    @Operation(summary = "激活账号：验证")
    public Result<String> JHYZEmail(@RequestHeader("Authorization") String token,@RequestParam String code){
        log.info("前端令牌为："+token);
        log.info("前端验证码为："+code);
        Map<String,Object> map =  jwt.parseToken(token);//解密jwt令牌
        String id = map.get("username").toString();
        String s = service.JHJYEmail(id, code);
        return Result.success(s);
    }

    @GetMapping("/JY")
    @Operation(summary = "校验账号状态")
    public Result<String> JY(@RequestHeader("Authorization") String token){
        Map<String,Object> map =  jwt.parseToken(token);//解密jwt令牌
        String id = map.get("username").toString();
        String jy = service.JY(id);
        return Result.success(jy);
    }

    @GetMapping("/GetEmail")
    @Operation(summary = "获取用户邮箱")
    public Result<String> GetEmail(@RequestHeader("Authorization") String token){
        Map<String,Object> map =  jwt.parseToken(token);//解密jwt令牌
        String id = map.get("username").toString();
        String s = service.GetEmail(id);
        email = s;
        return Result.success(s);
    }

    @GetMapping("/CPSendEmail")
    @Operation(summary = "修改密码部分：发送验证码")
    public Result<String> CPSendYZM(@RequestHeader("Authorization") String token){
        Map<String,Object> map =  jwt.parseToken(token);//解密jwt令牌
        String id = map.get("username").toString();
        String s = service.CPSendYZM(id, email);
        return Result.success(s);
    }

    @PostMapping("/CPJYEmail")
    @Operation(summary = "修改密码部分：校验验证码")
    public Result<String> CPJYYZM(@RequestHeader("Authorization") String token,@RequestBody String yzm){
        Map<String,Object> map =  jwt.parseToken(token);//解密jwt令牌
        String id = map.get("username").toString();
        String info = service.CPJYYZM(id, yzm);
        return Result.success(info);
    }

    @PostMapping("/ChangePassword")
    @Operation(summary = "修改密码")
    public Result<String> ChangePassword(@RequestHeader("Authorization") String token,@RequestBody String NewPassword){
        Map<String,Object> map =  jwt.parseToken(token);//解密jwt令牌
        String id = map.get("username").toString();
        String s = service.ChangePassword(id, NewPassword);
        if(s.equals("更新成功，请重新登陆！")){
            return Result.success(s);
        }
        else {
            return Result.error(s);
        }
    }

}
